package com.distribute.framework.core.web.helper;

import com.distribute.framework.core.web.helper.Utils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


@SuppressWarnings("unchecked")
public class ParamHelper {
	
	
	public static Map<String, Object> setString(Map<String,Object> params, String key, String value){
		String[] str={value};
		params.put(key, str);
		return params;
	}
	
	public static String getString(Map<String,Object> params, String key){
		return getString(params,key, null);
	}
	
	public static String getString(Map<String,Object> params, String key,String defaultValue){
		String temp = null;
		if(params.get(key)==null)
			return defaultValue;
		else if(params.get(key).getClass().isArray())
			temp = getArray(params,key)[0];
		else
			temp = params.get(key).toString();
		if(temp != null){			
			temp = temp.replaceAll("%", "\\%");
		}
		if(temp==null)
			return defaultValue;
		return temp;
	}
	
	public static Double getDouble(Map<String,Object> params, String key){
		return getDouble(params,key, null);
	}
	
	public static Double getDouble(Map<String,Object> params, String key, Double defaultValue){
		String value=getString(params,key);
		
		Double i=defaultValue;
		if(value == null || value.equals("")){
			return defaultValue;
		}
		try{
			i=new Double(value);
		}catch(Exception e){
			System.out.println("<ParamHelper error> - " + e.getMessage());
			i=defaultValue;
		}
		return i;
	}
	
	public static Integer getInteger(Map<String,Object> params, String key){
		return getInteger(params, key, null);
	}
	
	public static Integer getInteger(Map<String,Object> params, String key, 
			Integer defaultValue){
		String value=getString(params, key);
		Integer i=defaultValue;
		i=defaultValue;
		if(value == null || value.equals("")){
			return defaultValue;
		}
		try{
			i=new Integer(value);
		}catch(NumberFormatException e){
			System.out.println("<ParamHelper error> - " + e.getMessage());
		}
		return i;
	}
	public static Short getShort(Map<String,Object> params, String key){
		return getShort(params, key, null);
	}
	public static Short getShort(Map<String,Object> params, String key,Short defaultValue){
		String value=getString(params, key);
		Short i=defaultValue;
		i=defaultValue;
		if(value == null || value.equals("")){
			return defaultValue;
		}
		try{
			i=new Short(value);
		}catch(NumberFormatException e){
			System.out.println("<ParamHelper error> - " + e.getMessage());
		}
		return i;
	}
	
	
	public static Long getLong(Map<String,Object> params, String key){
		return getLong(params, key, null);
	}
	
	public static Long getLong(Map<String,Object> params, String key, 
			Long defaultValue){
		String value=getString(params, key);
		Long i=defaultValue;
		i=defaultValue;
		if(value == null || value.equals("")){
			return defaultValue;
		}
		try{
			i=new Long(value);
		}catch(NumberFormatException e){
			System.out.println("<ParamHelper error> - " + e.getMessage());
		}
		return i;
	}
	
	public static Byte getByte(Map<String,Object> params, String key){
		return getByte(params, key, null);
	}
	
	public static Byte getByte(Map<String,Object> params, String key,Byte defaultValue){
		Byte value=defaultValue;
		String s=getString(params, key, null);
		if(s == null || s.equals("")){
			return defaultValue;
		}
		if(s!=null){
			try{
				value=Byte.valueOf(s);
			}catch(NumberFormatException e){
				System.out.println("<ParamHelper error> - " + e.getMessage());
			}
		}
		return value;
	}
	
	public static Boolean getBoolean(Map<String,Object> params, String key)
	{
		return getBoolean(params, key, null);
	}
	
	public static Boolean getBoolean(Map<String,Object> params, String key,Boolean defaultValue)
	{
		Boolean b=defaultValue;
		String s=getString(params, key, null);
		if(s!=null && !s.trim().equals("")){
			try{
				b=Boolean.valueOf(s)||s.equals("1");
			}catch(NumberFormatException e){
				System.out.println("<ParamHelper error> - " + e.getMessage());
			}
		}
		return b;
	}

	public static Date getDate(Map<String,Object> params, String key){
		return getDate(params, key, null);
	}
	
	public static Date getDate(Map<String,Object> params, String key,Date defaultValue){
		Date date=null;
		String d=getString(params, key);
		if(d==null || "".equals(d)){
			date=defaultValue;
		}else{
			try{
				date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(d);
			}catch(Exception e){				
				try{
					date=new SimpleDateFormat("yyyy-MM-dd").parse(d);
				}catch(Exception ex){
					System.out.println("<ParamHelper error> - " + e.getMessage());
					System.out.println("<ParamHelper error> - " + ex.getMessage());
					date=defaultValue;
				}				
			}
		}
		return date;
	}

	public static String[] getArray(Map<String,Object> params,String key){
		return getArray(params, key, null);
	}	
	
	public static String[] getArray(Map<String,Object> params,String key,String[] defaultValue){
		if(params == null){
			return defaultValue;
		}
		if(params.get(key)==null)
			return defaultValue;
		try{
			if(params.get(key).getClass().isArray())
				return (String[]) params.get(key);
			else
				return new String[]{params.get(key).toString()};
		}catch(ClassCastException e){
			System.out.println("<ParamHelper error> - " + e.getMessage());
			return defaultValue;
		}
	}
	
	public static Float getFloat(Map<String,Object> params, String key){
		return getFloat(params, key, null);
	}
	
	public static Float getFloat(Map<String,Object> params, String key, Float defaultValue){
		String s=getString(params, key);
		Float value=defaultValue;
		if(s == null || s.equals("")){
			return defaultValue;
		}
		if(s!=null){
			try{
				value=Float.valueOf(s);
			}catch(Exception e){
				System.out.println("<ParamHelper error> - " + e.getMessage());
				value=defaultValue;
			}
		}
		return value;
	}
	
	public static Map getJson(Map<String,Object> params, String key){
		return getJson(params, key, null);
	}
	
	public static Map getJson(Map<String,Object> params, String key, Map defaultValue){
		String s=getString(params, key);
		Map value=defaultValue;
		if(s == null || s.equals("")){
			return defaultValue;
		}
		if(s!=null){
			try{
				value=(Map)JsonHelper.eval(s);
			}catch(Exception e){
				System.out.println("<ParamHelper error> - " + e.getMessage());
				value=defaultValue;
			}
		}
		return value;
	}
	
	/**
	 * 如果Class是基础类型，则直接根据key取值，
	 * 否则，Class是自定义类型，key则作为每个字段的前缀
	 * @param params
	 * @param key
	 * @param cls
	 * @return
	 * @throws Exception
	 */
	public static <T> T getObject(Map params,String key,Class<T> cls)
	{
		String classType = cls.getSimpleName();
		if(classType.equals("String"))
			return (T)ParamHelper.getString(params, key);
		else if(classType.equals("Date"))
			return (T)ParamHelper.getDate(params, key);
		else if(classType.equals("Boolean"))
			return (T)ParamHelper.getBoolean(params, key);
		else if(classType.equals("Byte"))
			return (T)ParamHelper.getByte(params, key);
		else if(classType.equals("Float"))
			return (T)ParamHelper.getFloat(params, key);
		else if(classType.equals("Double"))
			return (T)ParamHelper.getDouble(params, key);
		else if(classType.equals("Long"))
			return (T)ParamHelper.getLong(params, key);
		else if(classType.equals("Integer"))
			return (T)ParamHelper.getInteger(params, key);
		else if(classType.equals("Short"))
			return (T)ParamHelper.getShort(params, key);
		
		
		
		if(key!=null && !key.equals(""))
			key+=".";
		else
			key="";
		
		Object object=null;
		try {
			object = cls.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		Field[] fields = cls.getDeclaredFields();
		for(Field field:fields)
		{
			String fieldName = field.getName();
			String fieldType = field.getType().getSimpleName();
			
			Object fieldValue=null;
			if(fieldType.equals("String"))
				fieldValue=ParamHelper.getArrayToString(params, key+fieldName,",");
			else if(fieldType.equals("Date"))
				fieldValue=ParamHelper.getDate(params, key+fieldName);
			else if(fieldType.equals("Boolean"))
				fieldValue=ParamHelper.getBoolean(params, key+fieldName);
			else if(fieldType.equals("Byte"))
				fieldValue=ParamHelper.getByte(params, key+fieldName);
			else if(fieldType.equals("Float"))
				fieldValue=ParamHelper.getFloat(params, key+fieldName);
			else if(fieldType.equals("Double"))
				fieldValue=ParamHelper.getDouble(params, key+fieldName);
			else if(fieldType.equals("Long"))
				fieldValue=ParamHelper.getLong(params, key+fieldName);
			else if(fieldType.equals("Integer"))
				fieldValue=ParamHelper.getInteger(params, key+fieldName);
			else if(fieldType.equals("Short"))
				fieldValue=ParamHelper.getShort(params, key+fieldName);
			
			field.setAccessible(true);
			if(fieldValue!=null){
				try {
					field.set(object, fieldValue);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
		}
		
		return (T)object;
	}
	
	/**
	 * @author QZY
	 * @param params
	 * @param key
	 * @param defaultParamName
	 * @return
	 * @说明 把数据转为字符串, 用 defaultParamName 分割
	 */
	public static String getArrayToString(Map<String,Object> params,
			String key, String defaultParamName) {
		if(!params.containsKey(key))return null;
		String[] args = getArray(params,key);
		String str = "";
		if (args != null) {
			for (int i = 0; i < args.length; i++) {
				str = str + (i == 0 ? "" : defaultParamName)
						+ args[i];
			}
		}

		return str;
	}
	
	/** QZY add Struts2 ParamUtil END **/
	
	/**
	 * @author QZY
	 * @param params
	 * @return
	 * @说明 把 Map<String, String> 转为 Map<String, Object>
	 */
	public static Map<String, Object> convertParamsMap(Map<String, String> params){
		Map<String, Object> map=new HashMap<String, Object>();
		Iterator<String> iter=params.keySet().iterator();
		while(iter.hasNext()){
			String key=iter.next();
			String[] values={params.get(key)};
			map.put(key, values);
		}
		return map;
	}
	
	/**
	 * 获取分页的参数字符串
	 * @param params
	 * @param charset
	 * @param notAt
	 * @return
	 */
	public static String getQueryString(Map<String,Object> params,String charset,String... notAt){
		String query="";		
		if(params==null)
			return query;		
		Map notMap=new HashMap();
		for(String not:notAt)
			notMap.put(not, true);
		Iterator<String> iter=params.keySet().iterator();	
		while(iter.hasNext()){
			String key=iter.next();
			if(Utils.getRequest("notat."+key)!=null)
				continue;
			String[] array = ParamHelper.getArray(params, key);
			if(array!=null){
				for(String value:array){
					if(notMap.get(key)!=null)
						continue;
					if(value==null || value.equals(""))
						continue;
					try {
						value = URLEncoder.encode(value,charset);
					} catch (UnsupportedEncodingException e) {
						System.out.println("<ParamHelper error> - " + e.getMessage());
					}
					if(!query.equals(""))
						query+="&";
					query+=key+"="+value;
				}
			}
		}
		return query;
	}

}